package com.sanyou.service.impl;

import com.sanyou.mapper.VerticalityCheckRecordsMapper;
import com.sanyou.pojo.Product;
import com.sanyou.pojo.VerticalityCheckRecord;
import com.sanyou.pojo.dto.req.VerticalityCheckRecordUploadReq;
import com.sanyou.service.ProductService;
import com.sanyou.service.VerticalityCheckRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class VerticalityCheckRecordServiceImpl implements VerticalityCheckRecordService {
    @Autowired
    VerticalityCheckRecordsMapper verticalityCheckRecordsMapper;

    @Autowired
    ProductService productService;



    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void addRecord(VerticalityCheckRecord record) {
        if(record.getDateTime() == null){
            record.setDateTime(new Date());
        }
        verticalityCheckRecordsMapper.insert(record);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void uploadRecord(VerticalityCheckRecordUploadReq recordUploadReq) throws Exception {
        /**
         * 判断数据是否已经存在
         */
        if(getRecordByProductCode(recordUploadReq.getProductCode())!=null){
            throw new Exception("垂直度检测记录已存在");
        }

        /**
         * 插入垂直度检测数据
         */
        VerticalityCheckRecord record = new VerticalityCheckRecord();
        BeanUtils.copyProperties(recordUploadReq, record);
        addRecord(record);


        /**
         * 判断阴极板是否以及存在
         * 存在：更新阴极板垂直度
         * 不存在：新增阴极板
         */
        if (productService.getProductByCode(record.getProductCode()) == null){
            Product product = Product.builder()
                    .productCode(record.getProductCode())
                            .productValue(record.getMaxBias())
                                    .build();


            productService.addProduct(product);
        }else {
            Product product = productService.getProductByCode(record.getProductCode());
            product.setProductValue(record.getMaxBias());
            productService.updateProduct(product);
        }


    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public VerticalityCheckRecord getRecordByProductCode(String productCode) {
        if(StringUtils.isEmpty(productCode)){
            return null;
        }
        return verticalityCheckRecordsMapper.selectByProductCode(productCode);
    }


}
